$(document).ready(function() {
  $("input#id_email").focus();
  jQuery.validator.addMethod(
    "regexp",
    function(value, element, regexp) {
      var re = new RegExp(regexp);
      return this.optional(element) || re.test(value);
    },
    "Please check your input."
  );

  $("input[type='text'],input[type='password']").addClass("text");
  var email_url = $("#id_registration_form input#data-email-url").val();    
  var username_url = $("#id_registration_form input#data-username-url").val();

  $("#id_registration_form").validate({
      rules: {
        email: {
      	  required: true,
      	  email: true,
      	  remote: { 
            url: email_url, 
            type: "post" 
          }
      	},
      	new_username: {
      	  required: true,
      	  minlength: 2,
      	  maxlength: 32,
      	  regexp: "^([a-zA-Z0-9_]{2,32})$",
      	  remote: { 
	 	        url: username_url, 
	 	        type: "post" 
          } 
      	},
      	password1: {
      	  required: true,
      	  minlength: 6
      	},
      	password2: {
      	  required: true,
      	  minlength: 6,
      	  equalTo: "#id_password1"
      	}
            },
      messages: {
        email: {
      	  required: "Please enter a valid email address",
      	  minlength: "Your email is too short",
      	  maxlength: "Your email is too long",
      	  remote: "This email has been taken"
        },
      	new_username: {
      	  required: "Please choose an username",
      	  minlength: "Your username is too short",
      	  maxlength: "Your username is too long",
      	  regexp: "Only valid characters like a-z, A-Z, 0-9 or _ are allowed",
                remote: "This one is chosen, please pick another name"
      	},
      	password1: {
      	  required: "Please provide a password"
      	},
      	password2: {
      	  required: "Please repeat your password",
                equalTo: "Please enter the same password as above"
      	}  
      },
      success: function(label) {
        var id = label.attr("for");
        $("#" + id).addClass("valid").siblings("label").remove();
        label.text("Complete");
	      label.removeClass("jv_error error_text").addClass("valid");
	      $("#" + id).after(label);
      },
      errorClass: "jv_error error_text",
      validClass: "valid",
      errorPlacement: function(error, element) {
       element.removeClass("valid").siblings("label").remove();
        element.after(error);
      }
   });
});
